<?php

namespace App\Console\Commands;
use App\Models\Product;
use Elasticsearch\ClientBuilder;
use Illuminate\Console\Command;

class SyncProductToEs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync-product-to-es';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'sync product to es';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $productModel = new Product();
        $page = 1;
        $length = 1000;
        do{
            $offset = ($page - 1)*$length;

            $products = \DB::table($productModel->getTable())
                ->whereNull('delete_time')
                ->skip($offset)->take($length)
                ->get();

            $params = [
                'index' => \Config::get('elasticsearch.index'),
                'type' => $productModel->getTable(),
            ];
            foreach ($products as $product){
                $params['body'][] = [
                    'index' => [
                        '_index' => \Config::get('elasticsearch.index'),
                        '_type' => $productModel->getTable(),
                        '_id' => $product->id,
                    ]
                ];

                $params['body'][] = [
                    'goods_name' => $product->goods_name,
                    'taobao_title' => $product->taobao_title,
                    'tbid' => $product->tbid,
                    'taoke_price' => $product->taoke_price,
                    'quan_fee' => $product->quan_fee,
                    'tmall' => $product->tmall,
                    'sort' => $product->sort,
                    'is_top' => $product->is_top,
                    'update_time' => date('Y-m-d H:i:s', strtotime($product->update_time)),
                ];
            }
            if(isset($params['body']) && !empty($params['body'])) {
                $client = ClientBuilder::create()->setHosts(\Config::get('elasticsearch.hosts'))->build();
                $response = $client->bulk($params);
                \Log::debug(json_encode($response));
            }
            $page++;
        }while(!empty($products));
    }
}  